using System;
using System.IO;
using System.Text;
using System.Security.Cryptography;
using System.Text.RegularExpressions;

namespace AdaNNTP
{
	public class FileAssembler
	{
		public string outputPath {
			get;
			set;
		}
		
		public string encodedFileContents {
			get;
			set;
		}

        public File encodedAttachment { get; set; }
		
		private yEnc.YEncDecoder yEncDecoderType = new yEnc.YEncDecoder();
		
		public void Assemble()
		{
            yEncoding.yEncMessage yMessage = yEncoding.ProcessYencAttachment(encodedAttachment);
            //Console.WriteLine("File writing: " + outputPath + Path.DirectorySeparatorChar + yMessage.Filename);
            if (!Directory.Exists(outputPath) && !string.IsNullOrEmpty(outputPath))
                Directory.CreateDirectory(outputPath);

            outputPath = outputPath + Path.DirectorySeparatorChar.ToString() + yMessage.Filename;

            string regexSearch = new string(Path.GetInvalidFileNameChars()) + new string(Path.GetInvalidPathChars());
            Regex r = new Regex(string.Format("[{0}]", Regex.Escape(regexSearch)));
            outputPath = r.Replace(outputPath, "");



			FileStream outputStream = new FileStream(outputPath, FileMode.CreateNew);
			StreamWriter outputWriter = new StreamWriter(outputStream);

            outputWriter.Write(yMessage.Contents);
				
			outputWriter.Flush();
			outputStream.Flush();
			
			encodedFileContents = null;
			outputWriter.Close();
			outputStream.Close();
		}
	}
}

